<!--
 * @Author: zhangjingyu
 * @Date: 2020-12-07 17:44:54
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2020-12-23 10:29:15
 * @FilePath: \vprisk10.14\src\views\SystemMange\tenantManage.vue
 * @Description: 租户管理
-->
<template>
  <div>
    <!-- importIcon exportIcon -->
    <upper-template noSearchButton>
      <div slot="buttonArea">
        <el-button @click="addFunc">新增</el-button>
        <el-button @click="editFunc">编辑</el-button>
        <el-button @click="delFunc">删除</el-button>
        <el-button @click="authorizedEng">授权工程</el-button>
        <el-button @click="authorizUser">授权用户</el-button>
        <el-button @click="configEng">配置工程</el-button>
      </div>
      <div slot="searchArea">
        <onlyOneSearch
          v-model="searchForm.tennatName"
          placeholder="请输入租户名"
          :search-method="searchClick"
        ></onlyOneSearch>
      </div>
      <div slot="columnHide">
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="item in textData"
            :label="item.label"
            :key="item.prop"
            >{{ item.label }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </upper-template>
    <el-table
      ref="multipleTable"
      :data="tableData"
      style="width: 100%"
      @row-click="rowClick"
    >
      <el-table-column
        width="55"
        type="selection"
        
      ></el-table-column>
      <el-table-column
        prop="tennatName"
        label="租户名称"
        align="center"
        v-if="tablePick[0]"
      >
      </el-table-column>
      <el-table-column
        prop="orgDTO.orgName"
        label="机构"
        align="center"
        v-if="tablePick[1]"
      >
      </el-table-column>
      <el-table-column
        prop="tennatProjects"
        label="授权工程"
        v-if="tablePick[2]"
        :formatter="
          row => row.tennatProjects.map(v => v.projectName).toString()
        "
      >
      </el-table-column>

      <el-table-column
        prop="tennatUsers"
        label="授权用户"
        v-if="tablePick[3]"
        :formatter="row => row.tennatUsers.map(v => v.userName).toString()"
      >
      </el-table-column>
    </el-table>
    <pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchForm.page"
      :page-size="searchForm.size"
      @refresh="searchFunc"
      :total="total"
    ></pagination>

    <!-- 新增和编辑弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="saveTitles[saveFlg - 1]"
      :visible.sync="addOrEdit"
      width="514px"
    >
      <el-form
        :model="saveForm"
        @submit.prevent="false"
        ref="saveForm"
        label-width="100px"
        label-position="left"
        :rules="saveFormRules"
      >
        <el-form-item label="租户名称：" prop="tennatName">
          <el-input
            v-model="saveForm.tennatName"
            maxlength="40"
            :disabled="saveFlg === 2"
          ></el-input>
        </el-form-item>
        <el-form-item label="机构：" prop="orgId">
          <el-cascader
            clearable
            filterable
            :options="orgList"
            v-model="saveForm.orgId"
            :props="{
              checkStrictly: true,
              emitPath: false,
              expendTrigger: 'hover',
              value: 'orgId',
              label: 'orgName'
            }"
            :show-all-levels="false"
            ref="saveOrgTree"
            style="width:100%"
            @change="changeOrg"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="租户管理员：" prop="adminUserName">
          <el-input
            v-model="saveForm.adminUserName"
            readonly
            clearable
            style="width:70%;display:inline-block;margin-right:10px"
          ></el-input>
          <el-button
            icon="el-icon-plus"
            style="display:inline-block;"
            @click="showAddresseeList"
            >选择</el-button
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveFunc">确 定</el-button>
        <el-button @click="addOrEdit = false">取 消</el-button>
      </div>

      <el-dialog
      v-dialogDrag
        title="租户管理员选择"
        width="60%"
        :visible.sync="showUsers"
        append-to-body
      >
        <user-table ref="userTable" :inUse="inUse" :orgId="saveForm.orgId " ></user-table>
        <div slot="footer">
          <el-button @click="checkUsers">确定</el-button>
          <el-button @click="showUsers = false">关闭</el-button>
        </div>
      </el-dialog>
    </el-dialog>

    <!-- 工程授权弹窗 -->
    <el-dialog v-dialogDrag title="授权工程" width="514px" :visible.sync="projectDialog">
      <el-table :data="authProjectData" ref="authProjectData" @row-click="(row)=>{$refs.authProjectData.toggleRowSelection(row,true)}">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="projectName" label="工程"></el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="authCheckProjects">确定</el-button>
        <el-button @click="projectDialog = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 用户授权弹窗 -->
    <el-dialog v-dialogDrag title="授权用户" width="514px" :visible.sync="usersDialog">
      <el-table :data="authUsersData" ref="authUsersData" @row-click="(row)=>{$refs.authUsersData.toggleRowSelection(row,true)}">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="userName" label="用户"></el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="authCheckUsers">确定</el-button>
        <el-button @click="usersDialog = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 配置工程弹窗 -->
    <!-- 用户列表弹窗 -->
      <el-dialog v-dialogDrag title="用户列表" width="514px" :visible.sync="usersDialogEn" append-to-body>
      <el-button style="margin-bottom:20px;" @click="configEnList">配置工程</el-button>
      <el-table :data="authUsersDataEn" ref="authUsersDataEn" @row-click="(row)=>{$refs.authUsersDataEn.toggleRowSelection(row,true)}">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="userName" label="用户"></el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="usersDialogEn = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 用户列表弹窗 -->
    <!--工程列表弹窗  -->
      <el-dialog v-dialogDrag title="工程列表" width="514px" :visible.sync="enDialogEn" append-to-body>
      <el-table :data="enDataEn" ref="enDataEn" @row-click="(row)=>{$refs.enDataEn.toggleRowSelection(row,true)}">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="projectName" label="工程"></el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="authCheckUsersEn">确定</el-button>
        <el-button @click="enDialogEn = false">关闭</el-button>
      </div>
    </el-dialog>

    <!--工程列表弹窗 -->

    <!-- 配置工程弹窗 -->
  </div>
</template>

<script>
import { systemManage } from "@/api/index";
import userTable from "./userManage";
export default {
  components: {
    userTable
  },
  data() {
    return {
      inUse: true,
      usersDialogEn: false,
      enDialogEn: false,
      addOrEdit: false,
      showUsers: false,
      projectDialog: false,
      usersDialog: false,
      currentRow: null,
      userRowEn: null,
      checkList: ["租户名称", "机构", "授权工程", "授权用户"],
      tableData: [],
      textData: [
        { prop: "tenantName", label: "租户名称" },
        { prop: "orgName", label: "机构" },
        { prop: "projects", label: "授权工程" },
        { prop: "users", label: "授权用户" }
      ],
      // 机构树
      orgList: [],
      saveFlg: false,
      saveTitles: ["新增租户", "修改租户"],
      searchForm: {
        page: 1,
        size: 15,
        tennatName: ""
      },
      total: 0,
      saveForm: {
        tennatId: "",
        tennatName: "",
        orgId: "",
        useFlag: "",
        adminUserId: "",
        adminUserName: ""
      },
      saveFormRules: {
        tennatName: [
          { required: true, message: "请输入数租户名称", trigger: "blur" },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9]{1,40}$/,
            message: "只能输入1-40位中文、字母、数字或下划线",
            trigger: "blur"
          },
          { validator: this.tennatNameValid, trigger: "blur" }
        ],
        orgId: [{ required: true, message: "请选择机构", trigger: "blur" }],
        adminUserName: [
          { required: true, message: "请选择用户", trigger: "blur" }
        ]
      },
      // 授权用户table
      authUsersData: [],
      // 授权工程table
      authProjectData: [],
      enDataEn: [],
      authUsersDataEn: []
    };
  },
  created() {
    this.getOrgList();
    this.$nextTick(() => {
      this.searchFunc();
    });
  },
  watch: {
    addOrEdit() {
      if (this.$refs["saveForm"]) {
        this.$refs["saveForm"].clearValidate();
      }
    }
  },
  computed: {
    tablePick() {
      return this.$tableDataPick(this.checkList, this.textData);
    }
  },
  methods: {
    tennatNameValid(rule, val, callback) {
      // 只在新增时校验
      if (this.saveFlg != 1) {
        callback();
        return;
      }
      let data = {
        tennatId: this.saveForm.tennatId,
        tennatName: val
      };
      systemManage.checkTennatName(data).then(res => {
        if (res.code == 200) {
          callback();
        } else {
          callback(new Error("名称已存在"));
        }
      });
    },
    // 获取机构数据
    getOrgList() {
      systemManage.getOrganTree().then(res => {
        // console.log(res, "机构");
        this.orgList = res;
      });
    },
    searchClick(){
      this.searchForm.page=1;
      this.searchFunc();
    },
    searchFunc() {
      let data = this.searchForm;
      systemManage.tennatQueryForPage(data).then(res => {
        if (res.code == 200) {
          this.tableData = res.datas.rows;
          this.total = res.datas.total;
        }
      });
    },
    clearFunc() {
      for (const key in this.searchForm) {
        this.searchForm[key] = "";
      }
      this.searchForm.page = 1;
      this.searchForm.size = 15;
    },
    rowClick(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
   
    addFunc() {
      this.saveFlg = 1;
      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.addOrEdit = true;
    },
    editFunc() {
      this.saveFlg = 2;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      this.saveForm.adminUserId = row.adminUserId;
      this.saveForm.adminUserName = row.adminUser.userName;
      this.saveForm.tennatId = row.tennatId;
      this.saveForm.orgId = row.orgDTO.orgId;
      this.saveForm.tennatName = row.tennatName;
      this.addOrEdit = true;
    },
    saveFunc() {
      this.$refs["saveForm"].validate(valid => {
        if (valid) {
          let data = {
            ...this.saveForm
          };
          data.orgDTO = {
            orgId: this.saveForm.orgId
          };
          systemManage.tennatSave(data).then(res => {
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.addOrEdit = false;
              this.searchFunc();
            } else {
              this.$message.error(res.message || "保存失败");
            }
          });
        }
      });
    },
    delFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确定要删除选中数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = { ids: selection.map(v => v.tennatId) };
          systemManage.tennatRemove(data).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    changeOrg(){
      this.saveForm.adminUserId = "";
      this.saveForm.adminUserName = "";

    },
    // 获取用户列表
    showAddresseeList() {
      if(!this.saveForm.orgId) {
        return this.$message.warning("请先选择机构")
      }
      this.showUsers = true;
        this.$nextTick(()=>{
        this.$refs.userTable.searchFunc()
      })
    },
    // 选择租户确定按钮处理
    checkUsers() {
      let selection = this.$refs.userTable.$refs.multipleTable.selection;
      if (selection.length != 1) return this.$message.warning("请选择一条");
      let row = selection[0];
      this.saveForm.adminUserId = row.userId;
      this.saveForm.adminUserName = row.userName;
      this.showUsers = false;
    },
    // 授权工程按钮
    authorizedEng() {
      let slection = this.$refs.multipleTable.selection;
      this.currentRow = slection[0];
      if (slection.length != 1) return this.$message.warning("请选择一条数据");
      this.projectDialog = true;
      let pjt = slection[0].tennatProjects; // 已选择用户
      // 查询所有可用工程
      systemManage.queryAllUsefulProject().then(res=>{
        if(res.code==200){
          this.authProjectData= res.datas;
          // 打对勾
          this.$nextTick(() => {
            this.$refs.authProjectData.clearSelection();
            for (let i = 0; i < this.authProjectData.length; i++) {
              for (let j = 0; j < pjt.length; j++) {
                if (pjt[j].projectId == this.authProjectData[i].projectId) {
                  this.$refs.authProjectData.toggleRowSelection(
                    this.authProjectData[i],
                    true
                  );
                }
              }
            }
          });
        }
      })
    },
     // 授权工程确定
    authCheckProjects(){
      let ids = this.$refs.authProjectData.selection.map(v=>v.projectId);
      let data = {tennatId:this.currentRow.tennatId,projectIds:ids}
      systemManage.tennatTennatMgrProject(data).then(res=>{
        if(res.code==200){
          this.$message.success('授权工程成功')
          this.projectDialog = false;
          this.searchFunc()
        }else{
          this.$message.error(res.message)
        }
      })
    },
    // 授权用户按钮
    authorizUser() {
      let slection = this.$refs.multipleTable.selection;
      this.currentRow = slection[0];
      if (slection.length != 1) return this.$message.warning("请选择一条数据");
      this.usersDialog = true;
      let users = slection[0].tennatUsers; // 已选择用户
      // 查询可管理用户
      let data = {
        orgId: slection[0].orgDTO.orgId,
        tennatId: slection[0].tennatId
      }
      systemManage.queryUserForTennat(data).then(res => {
        if (res.code == 200) {
          this.authUsersData = res.datas;
          // 打对勾
          this.$nextTick(() => {
            this.$refs.authUsersData.clearSelection();
            for (let i = 0; i < this.authUsersData.length; i++) {
              for (let j = 0; j < users.length; j++) {
                if (users[j].userId == this.authUsersData[i].userId) {
                  this.$refs.authUsersData.toggleRowSelection(
                    this.authUsersData[i],
                    true
                  );
                }
              }
            }
          });
        }
      });
    },
    //授权用户确定
    authCheckUsers() {
      let ids = this.$refs.authUsersData.selection.map(v=>v.userId);
      let data = {tennatId:this.currentRow.tennatId,userIds:ids}
      systemManage.tennatTennatMgrUser(data).then(res=>{
        if(res.code==200){
          this.$message.success('授权用户成功')
          this.usersDialog = false;
          this.searchFunc()
        }else{
          this.$message.error(res.message)
        }
      })
    },
    // 配置工程
    configEng() {
      let slection = this.$refs.multipleTable.selection;
      this.currentRow = slection[0];
      if (slection.length != 1) return this.$message.warning("请选择一条数据");
      this.usersDialogEn = true;
      let users = slection[0].tennatUsers; // 已选择用户
      // 查询可管理用户
      let data = {
        orgId: slection[0].orgDTO.orgId,
        tennatId: slection[0].tennatId
      }
      // systemManage.queryUserForTennat(data).then(res => {
         systemManage.queryUserByTennat(data).then(res => {
        if (res.code == 200) {
          this.authUsersDataEn = res.datas;
          // 打对勾
          // this.$nextTick(() => {
          //   this.$refs.authUsersDataEn.clearSelection();
          //   for (let i = 0; i < this.authUsersDataEn.length; i++) {
          //     for (let j = 0; j < users.length; j++) {
          //       if (users[j].userId == this.authUsersDataEn[i].userId) {
          //         this.$refs.authUsersDataEn.toggleRowSelection(
          //           this.authUsersDataEn[i],
          //           true
          //         );
          //       }
          //     }
          //   }
          // });
        }
      });
    },
    // 配置工程打开工程弹窗
    configEnList(){
       let selection = this.$refs.authUsersDataEn.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      this.userRowEn = selection[0];
      this.enDialogEn = true
      console.log(selection,'selection566')
      let pjt = this.currentRow.tennatProjects; // 已选择用户
      // 查询该租户下的工程
      let data = {
        tennatId:this.currentRow.tennatId
      }
      systemManage.queryProjectByTennat(data).then(res=>{
        if(res.code==200){
          this.enDataEn= res.datas;
          // 打对勾
          // this.$nextTick(() => {
          //   this.$refs.enDataEn.clearSelection();
          //   for (let i = 0; i < this.enDataEn.length; i++) {
          //     for (let j = 0; j < pjt.length; j++) {
          //       if (pjt[j].projectId == this.enDataEn[i].projectId) {
          //         this.$refs.enDataEn.toggleRowSelection(
          //           this.enDataEn[i],
          //           true
          //         );
          //       }
          //     }
          //   }
          // });
        }
      })



    },
    // 配置工程确定
    authCheckUsersEn() {
        let selection = this.$refs.enDataEn.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      let ids = this.$refs.enDataEn.selection.map(v=>v.projectId);
      // let data = {tennatId:this.currentRow.tennatId,projectIds:ids,}
      let data = {userId:this.userRowEn.userId,mgrIds:ids,tennatId:this.currentRow.tennatId}
      systemManage.saveMgrProjects(data).then(res=>{
        if(res.code==200){
          this.$message.success('授权工程成功')
          this.enDialogEn = false;
          // this.searchFunc()
        }else{
          this.$message.error(res.message)
        }
      })
    },
   
    handleSizeChange(val) {
      this.searchForm.size = val;
      this.searchFunc();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.searchForm.page = val;
      this.searchFunc();
      console.log(`当前页: ${val}`);
    }
  }
};
</script>

<style lang="scss" scoped>
</style>